package com.chb.config;

import com.chb.filters.JwtFilter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

/**
 * @author CHB
 * @createTime 2022-6-16 10:32
 */
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // 关闭请求跨域伪造
        http.csrf().disable();
        // 拦截路径
        http.authorizeRequests()
                .antMatchers("/login").permitAll()
                .anyRequest().authenticated();
        // security鉴权之前解析token
        http.addFilterBefore(jwtFilter(), UsernamePasswordAuthenticationFilter.class);
        // 禁用缓存
        http.headers().cacheControl();
        // 禁用session
        http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
        // 处理异常
        http.exceptionHandling()
                .accessDeniedHandler(accessDen())
                .authenticationEntryPoint(authenticationEntry());
    }


    /**
     * 认证
     * @author CHB
     * @date 2022-06-17 18:14:26
     * @return AuthenticationManager
     */
    @Bean
    @Override
    protected AuthenticationManager authenticationManager() throws Exception {
        return super.authenticationManager();
    }

    /**
     * 登录校验
     * @param auth
     * @author CHB
     * @date 2022-06-17 09:49:28
     * @return void
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(myUserDetailsConfig()).passwordEncoder(new BCryptPasswordEncoder());
    }

    @Bean
    public MyUserDetailsConfig myUserDetailsConfig(){
        return new MyUserDetailsConfig();
    }

    @Bean
    public JwtFilter jwtFilter(){
        return new JwtFilter();
    }

    // 鉴权失败
    @Bean
    public  AccessDen accessDen() {
        return new AccessDen();
    }
    // 登陆失败
    @Bean
    public AuthenticationEntry authenticationEntry() {
        return new AuthenticationEntry();
    }
}

